import cv2
import numpy as np
import matplotlib.pyplot as plt

####直方图均衡化算法(he)
def equalize_hist(img):
    lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
    l, a, b = cv2.split(lab)

    # 降低图像的对比度
    l = l.astype(np.float32) / 255.0
    l_low_contrast = np.power(l, 1 / 2.2) * 255.0

    # 将图像转换为uint8
    l_low_contrast = np.uint8(l_low_contrast)

    # 进行直方图均衡化
    l_he = cv2.equalizeHist(l_low_contrast)

    # 进行自适应直方图均衡化
    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
    l_clahe = clahe.apply(l_low_contrast)

    # 合并通道并转换回BGR色彩空间
    img_he = cv2.merge((l_he, a, b))
    img_he = cv2.cvtColor(img_he, cv2.COLOR_LAB2BGR)


    return img_he


# 读取原始图像
img = cv2.imread('images_origin/2.jpg')

# 将图像从BGR转换为LAB色彩空间
lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
l, a, b = cv2.split(lab)

#降低图像的对比度
l = l.astype(np.float32) / 255.0
l_low_contrast = np.power(l, 1 / 2.2) * 255.0

# 将图像转换为uint8
l_low_contrast = np.uint8(l_low_contrast)

# 进行直方图均衡化
l_he = cv2.equalizeHist(l_low_contrast)

# 进行自适应直方图均衡化
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
l_clahe = clahe.apply(l_low_contrast)

# 合并通道并转换回BGR色彩空间
img_he = cv2.merge((l_he, a, b))
img_he = cv2.cvtColor(img_he, cv2.COLOR_LAB2BGR)

img_clahe = cv2.merge((l_clahe, a, b))
img_clahe = cv2.cvtColor(img_clahe, cv2.COLOR_LAB2BGR)

##显示原始图像、降低对比度后的图像和均衡化后的图像
# plt.subplot(221), plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
# plt.title('Original Image'), plt.xticks([]), plt.yticks([])
#
# plt.subplot(222), plt.imshow(cv2.cvtColor(cv2.merge((np.uint8(l_low_contrast), a, b)), cv2.COLOR_LAB2RGB))
# plt.title('Low Contrast Image'), plt.xticks([]), plt.yticks([])
#
# plt.subplot(223), plt.imshow(cv2.cvtColor(img_he, cv2.COLOR_BGR2RGB))
# plt.title('Equalized Image'), plt.xticks([]), plt.yticks([])
#
# plt.subplot(224), plt.imshow(cv2.cvtColor(img_clahe, cv2.COLOR_BGR2RGB))
# plt.title('Adaptive Equalized Image'), plt.xticks([]), plt.yticks([])
# plt.show()
